package mylogger1

import (
	"errors"
	"fmt"
	"path"
	"runtime"
	"strings"
	"time"
)

type logLevel uint16


const (
	UNKNOWN logLevel = iota
	TRACE
	DEBUG
	INFO
	WARNING
	ERROR
	FATAL
)

func parseloglevel(s string) (logLevel,error){
	s = strings.ToLower(s)
	switch s {
	case "debug":
		return DEBUG, nil
	case "trace":
		return TRACE, nil
	case "info":
		return INFO, nil
	case "warning":
		return WARNING, nil
	case "error":
		return ERROR, nil
	case "fatal":
		return FATAL, nil
	default:
		err := errors.New("input loglevel invalid")
		return UNKNOWN, err
	}
}

func getLogString(lv logLevel) string {
	switch lv {
	case DEBUG:
		return "debug"
	case ERROR:
		return "error"
	case WARNING:
		return "warning"
	case INFO:
		return "info"
	case TRACE:
		return "trace"
	case FATAL:
		return "fatal"
	default:
		return "UNKNOWN"
	}

}

func getInfo(skip int)(funcName, fileName string, lineNo int){
	pc, file, lineNo, ok := runtime.Caller(skip)
	if !ok {
		fmt.Printf("runtime.caller() failed\n")
		return
	}
	funcName = runtime.FuncForPC(pc).Name()
	fileName = path.Base(file)
	return
}

func log(lv logLevel, format string, a ...interface{})  {
	msg := fmt.Sprintf(format, a...)
	now := time.Now()
	funcName, fileName, lineNo := getInfo(3)
	fmt.Printf("[%s] [%s] [%s:%s:%d] %s\n", now.Format("2006-01-02 15:04:05"),getLogString(lv),funcName,fileName, lineNo, msg)

}